package com.example.shixun.interceptor;


import com.example.shixun.pojo.Result;
import com.example.shixun.utils.JwtUtils;
import com.example.shixun.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Description: TODO
 * @Date: Created in 上午11:06 2023/6/19
 * @Modified By:
 */
@Component
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String token = request.getHeader("token");
//        System.out.println("Authen:"+token);
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
//        System.out.println(token);
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Class<?> declaringClass = method.getDeclaringClass();
        // 需要登录权限
        if (declaringClass.isAnnotationPresent(Login.class) ||
            method.isAnnotationPresent(Login.class) ||
            declaringClass.isAnnotationPresent(Teacher.class) ||
            method.isAnnotationPresent(Teacher.class)) {
                if (token == null) {
                    System.out.println();
                    ResponseUtil.out(response, Result.fail(5008,"未登录"));
                    return false;
                }
                if (!JwtUtils.checkToken(token)) {
                    ResponseUtil.out(response, Result.fail(50014,"登录失效"));
                    return false;
                }

        }
        // 进一步判断是否需要教师权限
        if (declaringClass.isAnnotationPresent(Teacher.class) || method.isAnnotationPresent(Teacher.class)) {
            String role = JwtUtils.getRole(token);
            if (!role.equals("teacher")) {
                ResponseUtil.out(response, Result.fail(50015,"权限不足"));
                return false;
            }
        }
        // 进一步判断是否需要管理员权限
        if (declaringClass.isAnnotationPresent(Admin.class) || method.isAnnotationPresent(Admin.class)) {
            String role = JwtUtils.getRole(token);
            if (!role.equals("admin")) {
                ResponseUtil.out(response, Result.fail(50015,"权限不足"));
                return false;
            }
        }
        return true;
    }
}